<template>
    <div>
        <el-row type="flex" justify="space-between" align="center">
            <el-breadcrumb separator="/" style="line-height:32px">
                <el-breadcrumb-item
                    :to="{ path: '/completeGraduationManagement/graduationQualificationAudit' }"
                >
                    结业换毕业审核
                </el-breadcrumb-item>
                <el-breadcrumb-item>
                    <span v-if="mode === 'AUDIT'">
                        {{ $t('graduationList.review') }}
                    </span>
                    <span v-else>{{ $t('graduationList.previewDetails') }}</span>
                </el-breadcrumb-item>
            </el-breadcrumb>
            <el-button type="text" @click="handleClick('CANCEL')">返回</el-button>
        </el-row>
        <el-card>
            <h2 slot="header">结业换毕业审核详情</h2>
            <stu-base-info :itemList="studentInfo"></stu-base-info>
            <div v-if="generalCourseTableData.length > 0" style="margin-bottom: 16px;">
                <edu-table
                    :data="generalCourseTableData"
                    :order="false"
                    :pagination="false"
                    border
                    :selection="false"
                    :merge="true"
                    :show-header="false"
                    :stripe="false"
                    style="width: 100%;"
                >
                    <edu-table-column
                        v-for="(item, key) in generalCourseTableData[1] &&
                            generalCourseTableData[1].data"
                        :key="key"
                        min-width="250"
                    >
                        <template slot-scope="scope">
                            <div v-if="scope.row.data[key]">
                                <div
                                    class="float-left"
                                    :style="{
                                        'font-weight': scope.$index == 0 ? 'bold' : '',
                                        width: '130spx',
                                        'text-align': 'right',
                                        'margin-right': '16px'
                                    }"
                                >
                                    {{ scope.row.data[key].labName }}:
                                </div>
                                <div class="float-left">
                                    {{
                                        `${scope.row.data[key].getCredit || 0}/${scope.row.data[key]
                                            .credit || 0}`
                                    }}
                                </div>
                            </div>
                        </template>
                    </edu-table-column>
                </edu-table>
            </div>
            <div v-if="suspendPlanCourseList.length > 0" style="margin-bottom: 16px;">
                <h3 class="title">必修课不及格课程情况</h3>
                <el-table
                    :header-cell-style="tableHeaderStyle"
                    :data="suspendPlanCourseList"
                    :span-method="objectSpanMethod"
                    :order="false"
                    :pagination="false"
                    :border="true"
                    :selection="false"
                    :stripe="false"
                    style="width: 100%;"
                >
                    <el-table-column
                        label="课程类别"
                        prop="labName"
                        show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column label="课程代码" prop="courseCode"></el-table-column>
                    <el-table-column
                        label="课程"
                        prop="courseName"
                        show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column label="学分" prop="credits" width="60"></el-table-column>
                    <el-table-column label="考核方式" prop="examModeI18n"></el-table-column>
                    <el-table-column label="成绩" prop="score" width="80"></el-table-column>
                    <el-table-column
                        label="成绩性质"
                        prop="examNature"
                        width="100"
                    ></el-table-column>
                    <el-table-column
                        label="成绩时间"
                        width="100"
                        prop="scoreTime"
                    ></el-table-column>
                    <el-table-column
                        label="替换课程"
                        prop="replaceCourseName"
                        show-overflow-tooltip
                    ></el-table-column>
                </el-table>
            </div>
            <div v-if="suspendOtherCourseList.length > 0" style="margin-bottom: 16px;">
                <h3 class="title">其它毕业后修读课程情况</h3>
                <edu-table
                    :header-cell-style="tableHeaderStyle"
                    :data="suspendOtherCourseList"
                    :order="false"
                    :pagination="false"
                    :selection="false"
                    :stripe="false"
                    style="width: 100%;"
                >
                    <edu-table-column label="课程类别" prop="labName"></edu-table-column>
                    <edu-table-column label="课程代码" prop="courseCode"></edu-table-column>
                    <edu-table-column label="课程" prop="courseName" width="120"></edu-table-column>
                    <edu-table-column label="学分" prop="credits"></edu-table-column>
                    <edu-table-column label="考核方式" prop="examModeI18n"></edu-table-column>
                    <edu-table-column label="成绩" prop="score" width="80"></edu-table-column>
                    <edu-table-column
                        label="成绩性质"
                        prop="examNature"
                        width="100"
                    ></edu-table-column>
                    <edu-table-column label="学年度" prop='studyYear' show-overflow-tooltip></edu-table-column>
                    <edu-table-column label="学期" prop="term"></edu-table-column>
                </edu-table>
            </div>
            <el-form
                ref="formData"
                :model="formData"
                label-position="right"
                style="margin-top:16px;"
                class="detail-form"
            >
                <el-row>
                    <el-col :span="8">
                        <el-form-item
                            label-width="120px"
                            label="审核结论："
                            prop="manualConclusion"
                            :rules="[
                                {
                                    required: true,
                                    message: '请选择审核结论',
                                    trigger: ['change', 'blur']
                                }
                            ]"
                        >
                            <span v-if="mode === 'VIEW'" style="font-weight:bold">
                                <span v-if="manualConclusion == 4">{{$t('graduationList.permanentClosure')}}</span>
                                <span v-else>{{formData.manualConclusionI18n }}</span>
                            </span>
                            <DictSelect
                                v-else
                                labelAll="请选择"
                                v-model="formData.manualConclusion"
                                :data="options.auditConclusionList"
                                @change="manualConclusionChange"
                            ></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col span="8">
                        <el-form-item
                            label-width="140px"
                            label=" "
                            :rules="[{ required: true, trigger: ['change', 'blur'] }]"
                        >
                            <el-checkbox
                                :disabled="mode === 'VIEW' || formData.manualConclusion == 2 || formData.manualConclusion == 4"
                                false-label="0"
                                true-label="1"
                                border 
                                size="medium"
                                v-model="formData.directedDegree"
                            >授予学位</el-checkbox>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-row type="flex" justify="end" style="margin-top:16px">
                <el-button  @click="handleClick('PREW')">上一位</el-button>
                <el-button  @click="handleClick('NEXT')">下一位</el-button>
                <el-button @click="handleClick('CANCEL')">取消</el-button>
                <el-button type="primary" v-if="mode === 'AUDIT'" @click="handleClick('SUBMIT')">
                    提交
                </el-button>
            </el-row>
        </el-card>
    </div>
</template>


<script>
let itemList = [
    {
        label: '姓名',
        key: 'name',
        value: ''
    },
    {
        label: '学号',
        key: 'studentId',
        value: ''
    },
    {
        label: '审核年份',
        key: 'graduationDate',
        value: ''
    },
    {
        label: '学院',
        key: 'facultyI18n',
        value: ''
    },
    {
        label: '专业',
        key: 'professionI18n',
        value: ''
    },
    {
        label: '学制',
        key: 'lengthSchooling',
        value: ''
    },
    {
        label: '绩点',
        key: 'scorePoint',
        value: ''
    },
    {
        label: '总学分',
        key: 'totalCredit',
        value: ''
    },
    {
        label: '原学院审核结论',
        key: 'orginManualConclusionI18n',
        value: ''
    },
    {
        label: '机审结果',
        key: 'machineConclusionI18n',
        value: ''
    }
]
import Bus from 'common/src/utils/bus'
import UTILS from 'common/src/utils/utils'
import { queryDic } from 'common/src/api/dictionary'
import stuBaseInfo from '../undergraduate/component/stuBaseInfo'
import {
    getMachineDetail,
    setReviewConclusion,
    findPreviousOrNextStep
} from 'common/src/api/graduationManagement/suspendToGraduateList'
export default {
    name: 'graduationQualificationAuditDetail',
    components: {
        'stu-base-info': stuBaseInfo
    },
    data() {
        return {
            mode: 'VIEW',
            lastPath: '',
            studentId: '',
            studentInfo: [],
            professionalTableData: [], //学分标准
            generalCourseTableData: [], //通识选修课学分标准
            suspendPlanCourseList: [], //必修不及格课程情况
            suspendOtherCourseList: [], //其他毕业后修读课程情况
            formData: {
                faculty: '',
                graduateTime:'',
                studentId: '',
                isOverseas: '0',
                manualConclusion: '',
                manualConclusionI18n: '',
                directedDegree: '', //是否授予学位 0：否，1：是
                reviewBatch: '',
                reviewBatchId: '',
                reviewAuthId: '',
                graduationDate: '',
                orginManualConclusion: ''
            },
            lastQueryForm:{},
            options: {
                auditConclusionList: [
                    {
                        value: '1',
                        label: '毕业'
                    },
                    {
                        value: '2',
                        label: '结业'
                    },
                    // {
                    //     value: '4',
                    //     label: '永久结业'
                    // }
                ]
            },
            manualConclusion: '',
            studentInfoSuspendInfo: {}
        }
    },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            vm.lastPath = from.path
        })
    },
    mounted() {
        let params = this.$route.query
        this.mode = params.mode
        this.formData.reviewBatch = params.currentBatch.reviewBatch
        this.formData.reviewBatchId = params.currentBatch.reviewBatchId
        this.formData.reviewAuthId = params.currentBatch.id
        this.formData.graduationDate = params.currentBatch.grade
        this.studentId = params.studentId
        this.lastQueryForm = params.queryForm
        this.queryMachineDetail();
    },
    methods: {
        async queryMachineDetail(studentId = this.studentId) {
            let { code, data } = await getMachineDetail(studentId)
            if (code !== 200) return
            this.studentId = data.studentID;
            this.formData.faculty = data.studentInfoSuspend && data.studentInfoSuspend.faculty
            this.formData.graduateTime = data.studentInfoSuspend && data.studentInfoSuspend.graduateTime
            if (data.studentInfoSuspend) {
                data.studentInfoSuspend.professionI18n = data.studentInfoSuspend.professionName || data.studentInfoSuspend.professionI18n;
            }
            itemList.forEach(
                item => (item.value = data.studentInfoSuspend && data.studentInfoSuspend[item.key])
            )
            this.studentInfo = itemList;
            this.studentInfoSuspendInfo = data.studentInfoSuspend || {};
            this.manualConclusion = data.studentInfoSuspend && data.studentInfoSuspend.manualConclusion || '';
            this.formData.manualConclusionI18n = data.studentInfoSuspend
                ? data.studentInfoSuspend.manualConclusionI18n
                : ''
            this.formData.directedDegree = data.studentInfoSuspend
                ? data.studentInfoSuspend.directedDegree
                : ''
            this.handleElectiveStandard(data.electiveStand)
            this.suspendPlanCourseList = data.suspendPlanCourseList
                ? data.suspendPlanCourseList
                : []
            this.mergeRow(this.suspendPlanCourseList)
            this.suspendOtherCourseList = data.suspendOtherCourseList
                ? data.suspendOtherCourseList
                : []
        },
        mergeRow(originData) {
            if (!originData) return
            let listMap = originData.reduce((pre, cur, index) => {
                return {
                    ...pre,
                    [cur.labID]: pre[cur.labID] ? [...pre[cur.labID], cur] : [cur]
                }
            }, {})
            for (let key in listMap) {
                let index = originData.findIndex(item => item.labID == key)
                originData[index].isFirst = true
                originData[index].len = listMap[key].length
            }
        },
        goBack() {
            this.$store.commit('delete_tabs', this.$route.path)
            this.$router.push({
                path: '/completeGraduationManagement/graduationQualificationAudit'
            })
        },
        /**
         * 查询当前学生上一位、下一位的学生id
         * step 0:下一步；1：上一步
         * isOverseas 0:国内生；1留学生
         * currentStudentId :当前学生ID
         */
        async getStudentId(currentStudentId = '', step = 0) {
            let { code, data } = await findPreviousOrNextStep({...this.lastQueryForm,currentStudentId, step})
            if (code !== 200) return
            if (!data) {
                let msg
                if (!step) {
                    msg = '已经是最后一位学生了'
                } else {
                    msg = '已经是最前一位学生了'
                }
                this.$message({
                    type: 'warning',
                    message: msg
                })
            } else {
                this.studentId = data;
                this.resetData();
                this.queryMachineDetail()
            }
        },
        handleClick(type) {
            let _this = this
            let actions = {
                CANCEL: function() {
                    _this.goBack()
                },
                PREW: function() {
                    _this.getStudentId(_this.studentId,1)
                },
                NEXT: function() {
                    _this.getStudentId(_this.studentId,0)
                },
                SUBMIT: function() {
                    const stant_1 = 1;
                    const stant_2 = 2;
                    // 元审核结论为毕业则不能选择结业
                    if ((_this.studentInfoSuspendInfo.orginManualConclusion == stant_1 || _this.studentInfoSuspendInfo.collegeAuditConclusion == stant_1) && _this.formData.manualConclusion == stant_2) {
                        _this.$message({
                            type: 'warning',
                            message: '审核结论为毕业的不能再审核为结业。'
                        })
                        return;
                    }
                    _this.formData.studentId = _this.studentId;
                    _this.formData.orginManualConclusion = _this.studentInfoSuspendInfo.orginManualConclusion;
                    _this.$refs['formData'].validate(valid => {
                        if (valid) {
                            _this.request(setReviewConclusion(_this.formData))
                        } else {
                            return false
                        }
                    })
                }
            }
            return actions[type]()
        },
        async request(api) {
            let { code, data } = await api
            if (code !== 200) return
            this.$message({
                type: 'success',
                message: '提交成功'
            })
            this.goBack()
        },
        handleLabelStandard(data) {
            if (!data || !data.length) {
                return
            }
            let labIdMap = {}
            let totalItem = null
            let list = data.filter(item => {
                item.credit = item.credit || 0
                if (item.orderNum === 999) {
                    totalItem = item
                } else {
                    if (!item.parentLabID) {
                        let labID = item.labID + '_'
                        if (!labIdMap[labID]) {
                            labIdMap[labID] = []
                        }
                        labIdMap[labID].push(item)
                    } else {
                        let parentLabID = item.parentLabID + '_'
                        if (!labIdMap[parentLabID]) {
                            labIdMap[parentLabID] = []
                        }
                        labIdMap[parentLabID].push(item)
                    }
                }
                return item.orderNum !== 999
            })
            let newList = [
                {
                    courseCategory: '已完成学分',
                    data: []
                },
                {
                    courseCategory: this.$t('auditStandard.creditTotal'),
                    data: []
                },
                {
                    courseCategory: this.$t('auditStandard.totalCredits'),
                    data: [totalItem]
                }
            ]
            for (let key in labIdMap) {
                labIdMap[key].sort((item1, item2) => {
                    return item2.orderNum - item1.orderNum
                })
                let len = newList[1].data.length
                if (labIdMap[key] && labIdMap[key].length > 1) {
                    let num = 0
                    let parentCredit = 0
                    let parentItem = null
                    labIdMap[key].forEach(v => {
                        if (v.parentLabID) {
                            newList[0].data.push(v)
                            if (v.credit) {
                                parentCredit += Number(v.credit)
                            }
                            num++
                        } else {
                            parentItem = v
                            newList[1].data.push(v)
                        }
                    })
                    parentItem && (parentItem.credit = parentCredit)
                    if (!newList[1].columnList) {
                        newList[1].columnList = []
                    }
                    num > 1 &&
                        newList[1].columnList.push({
                            index: len + 1,
                            rowspan: 1,
                            colspan: num
                        })
                } else {
                    if (labIdMap[key].length === 1) {
                        newList[0].data.push(labIdMap[key][0])
                        newList[1].data.push(labIdMap[key][0])
                    }
                }
            }
            let totalNum = newList[0].data.length
            newList[2].columnList = [
                {
                    index: 1,
                    rowspan: 1,
                    colspan: totalNum
                }
            ]
            this.professionalTableData = newList
        },
        handleElectiveStandard(param) {
            if (!param || !param.length) {
                return
            }
            let totals = 0
            let totalGetCredit = 0;
            let data = param.filter(v => {
                if (v.orderNum === 999) {
                    totals = v.credit
                    totalGetCredit = v.getCredit || 0;
                }
                return v.orderNum !== 999
            })
            let len = data.length
            let index = 1
            let list = [
                {
                    data: [
                        {
                            labName: this.$t('auditStandard.creditStandardGeneralCourses'),
                            credit: 0,
                            getCredit: totalGetCredit
                        }
                    ]
                }
            ]
            let calcuTotal = 0
            for (let i = 0; i < len; i++) {
                data[i].credit && (calcuTotal += Number(data[i].credit))
                if (i !== 0 && i % 4 === 0) {
                    index++
                }
                if (!list[index]) {
                    list[index] = {
                        data: []
                    }
                }
                data[i].credit = data[i].credit || 0
                list[index].data.push(data[i])
            }
            ;(list[0].columnList = [
                {
                    index: 0,
                    rowspan: 1,
                    colspan: list[1].data.length
                }
            ]),
                (list[0].data[0].credit = totals || calcuTotal)
            this.generalCourseTableData = list
        },
        tableHeaderStyle({ row, column, rowIndex, columnIndex }) {
            return 'background-color:#EEF7FF;font-weight:400;'
        },
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 0) {
                if (row.isFirst) {
                    return {
                        rowspan: row.len,
                        colspan: 1
                    }
                } else {
                    return {
                        rowspan: 0,
                        colspan: 0
                    }
                }
            }
        },
        resetData() {
            Object.assign(this.$data, {
                studentInfo: [],
                professionalTableData: [], 
                generalCourseTableData: [],
                suspendPlanCourseList: [], 
                suspendOtherCourseList: []
            })
        },
        manualConclusionChange() {
            if (this.formData.manualConclusion == 2 || this.formData.manualConclusion == 4) {
                this.formData.directedDegree = ''
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.title {
    font-weight: bold !important;
}
.row_remark {
    line-height: 32px;
    font-size: 14px;
    font-weight: 400;
    border-bottom: 1px solid #dadcde;
}
::v-deep .detail-form {
    .el-form-item__label, .el-form-item__content .el-checkbox{
        font-weight: bold;
    }
}
</style>